package com.sunda.spmsweb.usercontroller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.service.*;
import com.sunda.spmsweb.oaservice.OaService;
import com.sunda.spmsweb.util.MD5Utils;
import com.sunda.spmswms.service.IWerksService;
import com.sunda.spmswms.service.IWhsService;
import com.sunda.spmswms.service.IWorkshopService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

import static com.sunda.spmscommon.Constans.SUCCESS;

/**
 * <p>
 * SPMS用户信息表 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-01-25
 */
@RestController
@RequestMapping("/spmsUser")
@Api(tags = "系统用户接口", description = "系统用户接口")
public class SpmsUserController {

    @Autowired
    ISpmsUserService iSpmsUserService;

    @Autowired
    ISpmsRoleService iSpmsRoleService;

    @Autowired
    ISpmsUserWhsService iSpmsUserWhsService;

    @Autowired
    ISpmsUserWorkshopService iSpmsUserWorkshopService;

    @Autowired
    IWhsService iWhsService;
    @Autowired
    IWorkshopService iWorkshopService;

    @Autowired
    IWerksService iWerksService;

    @Autowired
    ISpmsPermissionService iSpmsPermissionService;

    @RequestMapping("/getUserListByPage")
    @ApiOperation(value = "获取全部用户分页信息",notes = "获取全部用户分页信息", httpMethod = "GET")
    public ResponseResult getUserListByPage(@RequestParam(defaultValue = "1") int pageNo ,
                                            @RequestParam(defaultValue = "20") int pageSize) {
        Page<SpmsUser> page = new Page<>(pageNo,pageSize);
        try{
            return ResponseResult.success().add("pageInfo", iSpmsUserService.spmsUserList(page));
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getAllUserList")
    @ApiOperation(value = "获取全部用户信息不分页",notes = "获取全部用户信息不分页", httpMethod = "GET")
    public ResponseResult getAllUserList() {
        try{
            return ResponseResult.success().add("spmsUserList", iSpmsUserService.getAllSpmsUserList());
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/userProfile")
    @ApiOperation(value = "获取用户配置信息SPMS",notes = "根据用户工号获取用户配置信息，如果系统存在则返回用户在本系统配置信息，" +
            "如果不存在则从OA请求用户信息。userId = 999950",
            httpMethod = "POST")
    public ResponseResult userProfile(@RequestParam String userId) {
        try{
            SpmsUser userInfo = iSpmsUserService.getByUserId(userId);
            if (userInfo != null && userInfo.toString().length() > 0){
                List<Map<String, Object>> roleList = iSpmsRoleService.getRoleById(userId);
                List<Map<String, Object>> userWhs = iSpmsUserWhsService.getUserWhsList(userId);
                List<Map<String, Object>> userWorkshop = iSpmsUserWorkshopService.getUserWorkshopList(userId);
                return ResponseResult.success()
                        .add("userInfo", userInfo)
                        .add("userRole", roleList)
                        .add("userWhs", userWhs)
                        .add("userWorkshop", userWorkshop);
            }else {
                OaService oaService = new OaService();
                Map<String, Object> map = oaService.getUserInfo(userId);
                if (map == null){
                    return ResponseResult.error();
                }
                return ResponseResult.success().add("userInfo", map);
            }
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getUserInfo")
    @ApiOperation(value = "根据工号获取用户详细信息OA",notes = "获取指定工号的用户详细信息，示例 userId = 999950",
            httpMethod = "POST")
    public ResponseResult getOrderScenario(String userId) {
        OaService oaService = new OaService();
        try{
            Map<String, Object> map = oaService.getUserInfo(userId);
            if (map == null){
                return ResponseResult.error("从OA获取用户信息失败");
            }
            return ResponseResult.success().add("userInfo", map);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/createSpmsUser")
    @ApiOperation(value = "新增/更新用户",notes = "新增或更新用户，传入JSON字符串格式，传入参数示例中：userId 必填，其余字段值可选。\n" +
            "loginPassword 后台默认 123456，传值会被忽略\n" +
            "{\n" +
            "\t\"userInfo\": {\n" +
            "\t\t\"userId\": \"20001\",\n" +
            "\t\t\"workId\": \"20001\",\n" +
            "\t\t\"lastName\": \"20001\",\n" +
            "\t\t\"telephone\": \"13866668888\",\n" +
            "\t\t\"mobile\": \"13866668888\",\n" +
            "\t\t\"email\": \"sunda@sunda.com\",\n" +
            "\t\t\"positionId\": \"11\",\n" +
            "\t\t\"positionName\": \"position name\",\n" +
            "\t\t\"deptId\": \"123\",\n" +
            "\t\t\"deptName\": \"dept name\",\n" +
            "\t\t\"subcompanyId\": \"1234\",\n" +
            "\t\t\"subcompanyName\": \"subcompany id\",\n" +
            "\t\t\"company\": \"company\",\n" +
            "\t\t\"branchPoint\": \"12345\",\n" +
            "\t\t\"branchLine\": \"123456\",\n" +
            "\t\t\"managerId\": \"10000\",\n" +
            "\t\t\"managerName\": \"10000\",\n" +
            "\t\t\"oaStatus\": \"1\",\n" +
            "\t\t\"spmsStatus\": \"1\"\n" +
            "\t},\n" +
            "\t\"userRole\": [{\n" +
            "\t\t\"uuid\": \"161556d97ae44139ad21659c5fb98e00\",\n" +
            "\t\t\"roleId\": \"1001\"\n" +
            "\t}],\n" +
            "\t\"userWhs\": [{\n" +
            "\t\t\"werks\": \"CN01\",\n" +
            "\t\t\"whsLocationCode\": \"1061\"\n" +
            "\t}],\n" +
            "\t\"userWorkshop\": [{\n" +
            "\t\t\"werks\": \"GH01\",\n" +
            "\t\t\"workshopCode\": \"1002\"\n" +
            "\t}]\n" +
            "}", httpMethod = "POST")
    @ApiImplicitParam(name = "jsonObject", value = "JSONObject 示例字符串", dataTypeClass = String.class, required = true, paramType = "body", dataType = "string")
    public ResponseResult createSpmsUser(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("userInfo") || jsonObject.getString("userInfo").length() == 0){
            return ResponseResult.error("参数错误请重试！");
        }
        JSONObject userInfo = jsonObject.getJSONObject("userInfo");
        if (!userInfo.containsKey("userId") || userInfo.getString("userId").length() == 0){
            return ResponseResult.error("参数错误请重试！");
        }
        String userId = userInfo.getString("userId");
        //String loginPassword = userInfo.getString("loginPassword");
        String MDPassword = MD5Utils.encrypt(userId, "12345678");
        return iSpmsUserService.createSpmsUser(jsonObject, MDPassword);

    }

    @RequestMapping("/updatePassword")
    @ApiOperation(value = "更新登录密码",notes = "更新登录密码", httpMethod = "GET")
    public ResponseResult updatePassword(String userId, String password) {
        try{
            return iSpmsUserService.updatePassword(userId, MD5Utils.encrypt(userId, password));
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getWerksInfo")
    @ApiOperation(value = "获取全部工厂仓库车间角色信息",notes = "获取全部工厂仓库车间角色基本信息",
            httpMethod = "GET")
    public ResponseResult getWerksInfo() {
        try{
            return ResponseResult.success().add("whsInfo", iWhsService.getWhsList())
                    .add("workshopInfo", iWorkshopService.getWorkshopList())
                    .add("roleList", iSpmsRoleService.getRoleList())
                    .add("allWerks",iWerksService.getWerksList());
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getRolePerm")
    @ApiOperation(value = "获取全部角色权限信息",notes = "获取全部权限表信息、全部角色权限关系表信息",
            httpMethod = "GET")
    public ResponseResult getRolePerm() {
        try{
            return ResponseResult.success().add("rolePermList", iSpmsPermissionService.getRolePerm())
                    .add("permissionList", iSpmsPermissionService.getAllPerm());
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateSpmsUserInfo")
    @ApiOperation(value = "实时同步用户OA信息到SPMS",notes = "实时同步用户OA信息到SPMS",
            httpMethod = "GET")
    public ResponseResult updateSpmsUserInfo(String userId) {
        if (StringUtils.isEmpty(userId)){
            return ResponseResult.error("请求参数不能为空");
        }
        try{
            OaService oaService = new OaService();
            Map<String, Object> map = oaService.getUserInfo(userId);
            if (map == null || map.size() == 0){
                return ResponseResult.error("OA返回信息错误");
            }
            return iSpmsUserService.updateSpmsUserInfo(map);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateAllSpmsUserInfo")
    @ApiOperation(value = "一键同步所有用户OA信息到SPMS",notes = "一键同步所有用户OA信息到SPMS",
            httpMethod = "GET")
    public ResponseResult updateAllSpmsUserInfo() {
        try{
            List<SpmsUser> spmsUserList = iSpmsUserService.getAllSpmsUserList();
            int re = 0;
            for (SpmsUser spmsUser : spmsUserList){
                OaService oaService = new OaService();
                Map<String, Object> map = oaService.getUserInfo(spmsUser.getUserId());
                System.out.println(map);
                if (map != null && map.size() > 0){
                    ResponseResult updateResult = iSpmsUserService.updateSpmsUserInfo(map);
                    if (updateResult.getCode() == SUCCESS){
                        re += 1;
                    }
                }
            }
            return ResponseResult.success("更新完成").add("系统用户总数：", spmsUserList.size()).add("此次更新人数：", re);
        } catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

}
